/*
 * DirVideoSource.cpp
 *
 *  Created on: 2018年3月19日
 *      Author: zhengboyuan
 */

#include "DirVideoSource.h"
#include "Path.h"


DirVideoSource::DirVideoSource(const std::string& filepath):
	m_size(720, 576),
	m_filepath(filepath),
	m_index()
{
}

DirVideoSource::~DirVideoSource()
{
}


void DirVideoSource::setSize(const cv::Size& size)
{
	if (size.width > 0 && size.height > 0)
	{
		m_size = size;
	}
}

cv::Size DirVideoSource::getSize()
{
	return m_size;
}

bool DirVideoSource::getFrame(cv::Mat& frame)
{
	std::vector< std::string > names;
	comn::Path::listFile(m_filepath, names);
	if (names.empty())
	{
		return false;
	}

	for (size_t i = 0; i < names.size(); i++)
	{
		size_t idx = (i + m_index) % names.size();
		std::string name = names[idx];
		if (isSupported(name))
		{
			m_index = idx + 1;

			std::string filepath = comn::Path::join(m_filepath, name);
			return readFrame(filepath, frame);
		}
	}
	
	return false;
}

bool DirVideoSource::isOpened()
{
	return comn::Path::exist(m_filepath);
}

void DirVideoSource::setPath(const char* filepath)
{
	m_filepath = filepath;
}

bool DirVideoSource::isSupported(const std::string& filename)
{
	std::string ext = comn::Path::getFileExt(filename);
	const char* extList[] = 
	{
		".jpg", ".png", ".bmp"
	};

	size_t count = sizeof(extList) / sizeof(extList[0]);
	for (size_t i = 0; i < count; i++)
	{
		if (ext == extList[i])
		{
			return true;
		}
	}
	return false;
}

bool DirVideoSource::readFrame(const std::string& filepath, cv::Mat& frame)
{
	cv::Mat mat = cv::imread(filepath);
	if (mat.empty())
	{
		return false;
	}

	if (mat.size() == m_size)
	{
		frame = mat;
	}
	else
	{
		cv::resize(mat, frame, m_size);
	}

	return true;
}